package com.ambitor.ipro.actions;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.SkyenccUtil;
import com.ambitor.ipro.util.TableName;
import com.ambitor.ipro.util.Utils;
import com.taobao.api.domain.User;
import com.taobao.api.domain.UserSubscribe;

public class TopAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private TopService topService;

	private SuperDao superDao = null;

	private String userId = null;

	private String nick = null;

	private String shopURL = null;

	private String sessionId = null;

	public TopAction() throws SQLException {
		superDao = new SuperDaoImpl(pd.getConn());
		topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IMPROMOTION, Constants.APP_SECRET_IMPROMOTION);
	}

	@Override
	@SuppressWarnings("unchecked")
	public String execute() throws Exception {
		// 验证参数签名
		if (validSign() == false) {
			return LOGIN;
		}
		logger.info(nick + "签名验证通过");

		// 验证用户使用权限是否到期
		if (validUserSubsc() == false) {
			return LOGIN;
		}
		logger.info(nick + "订购验证通过");

		// 验证用户是否有店铺，没有店铺禁止登录
		shopURL = topService.getShopURL(nick);
		pd.setSessionAttribute(Constants.SESSION_SHOP, shopURL);
		if ("#".equals(shopURL))
			return LOGIN;

		// 新增或更新用户信息
		addOrUpdateUser();

		// 记录登录日志
		loginLog();

		return SUCCESS;
	}

	private boolean validSign() {
		boolean isSignValid = true;
		String appKey = pd.getRequestParameter("top_appkey");
		String parameters = pd.getRequestParameter("top_parameters");
		sessionId = pd.getRequestParameter("top_session");
		String sign = pd.getRequestParameter("top_sign");

		Map<String, String> params = new HashMap<String, String>();
		params.put("top_appkey", appKey);
		params.put("top_parameters", parameters);
		params.put("top_session", sessionId);

		try {
			isSignValid = SkyenccUtil.validateSign(sign, params,
					Constants.APP_SECRET_IMPROMOTION);
		} catch (Exception e) {
			logger.warn("validateSign验证失败,打印请求参数：");
			logger.warn("top_appkey==" + appKey);
			logger.warn("top_parameters==" + parameters);
			logger.warn("top_session==" + sessionId);
			logger.warn("top_sign==" + sign);
			logger.warn("validateSign验证失败,请求参数打印完毕.");
			isSignValid = false;
			return isSignValid;
		}

		Map<String, String> userParam = null;
		if (isSignValid) {
			logger.info("validateSign验证通过，确认请求是从taobao.com发过来的.");
			userParam = SkyenccUtil.convertBase64StringtoMap(parameters);
			userId = userParam.get("visitor_id");
			nick = userParam.get("visitor_nick");
		}
		return isSignValid;
	}

	private boolean validUserSubsc() throws NumberFormatException,
			UnsupportedEncodingException {
		UserSubscribe userSubs = null;
		try {
			userSubs = topService.getSubscribeInfo(nick, Constants.LEASE_ID);
		} catch (Exception e) {
			logger.warn("获取" + nick + "订购信息过程中出现异常", e);
		}

		Result versionInfo = Utils.getUserClass(superDao, userId, userSubs);
		if (versionInfo.getCode() < 0) {
			return false;
		}
		pd.setSessionAttribute(Constants.SESSION_USER_SUBSCRIBE, versionInfo);

		int leftDays = Utils.daysBetween(new Date(), userSubs.getEndDate());
		pd.setSessionAttribute("session_taobao_version", userSubs.getVersionNo()+"");
		pd.setSessionAttribute("session_left_days", leftDays);

		String welcomInfo = Utils.builderOrderStr(versionInfo);
		pd.setSessionAttribute(Constants.SESSION_USER_SUBSCRIBE_INFO,
				welcomInfo);
		pd.setSessionAttribute(Constants.SESSION_NICK, nick);
		return true;
	}

	@SuppressWarnings("unchecked")
	private void addOrUpdateUser() {
		IData userSession = new DataMap();
		IData topParams = new DataMap();
		topParams.put("USER_ID", userId);
		try {
			userSession = superDao.queryByPK(TableName.TF_P_USER_SESSION,
					topParams);
		} catch (Exception e) {
			logger.warn("获取TF_P_USER_SESSION出错", e);
		}

		User user = topService.getUser(nick, sessionId);
		topParams.put("NICK", nick);
		topParams.put("SESSION_ID", sessionId);
		topParams.put("LAST_VALID_TIME", pd.getTime());
		topParams.put("VALID_FLAG", Constants.FLAG_YES);
		topParams.put("FIRST_INVALID_TIME", null);
		topParams.put("IS_HANDLED", null);
		topParams.put("HANDLE_TIME", null);
		topParams.put("HANDLE_TYPE", null);
		topParams.put("SHOP_URL", shopURL);
		topParams.put("PROV", user.getLocation().getState());
		topParams.put("CITY", user.getLocation().getCity());
		topParams.put("SHOP_TYPE", user.getType());
		topParams.put("SELLER_CREDIT_LEVEL", user.getSellerCredit().getLevel());
		topParams.put("SELLER_CREDIT_SCORE", user.getSellerCredit().getScore());
		topParams.put("EMAIL", user.getEmail());
		topParams.put("ALIPAY_ACCOUNT", user.getAlipayAccount());

		if (userSession.size() <= 0) {// 新增
			logger.info("user_sesssion表中不存在" + userId + "(" + nick + ")"
					+ "的信息,将insert一条");
			topParams.put("FIRST_LOGIN_TIME", pd.getTime());
			try {
				superDao.insert(TableName.TF_P_USER_SESSION, topParams);
			} catch (Exception e) {
				logger.warn("新增TF_P_USER_SESSION出错", e);
			}
		} else {// 更新
			logger.info("user_sesssion表中已存在" + userId + "(" + nick + ")"
					+ "的信息");
			try {
				superDao.update(TableName.TF_P_USER_SESSION, topParams);
			} catch (Exception e) {
				logger.warn("更新TF_P_USER_SESSION出错", e);
			}
			logger.info("已经更新" + TableName.TF_P_USER_SESSION + "中的信息");
		}
		pd.setSessionAttribute(Constants.SESSION_TOP, topParams);
		logger.info("把请求参数topParams保存到session中");
	}

	@SuppressWarnings("unchecked")
	private void loginLog() {
		IData login = new DataMap();
		HttpServletRequest request = pd.getRequest();
		login.put("USER_ID", userId);
		login.put("NICK", nick);
		login.put("LOG_TYPE", "0");
		login.put("LOG_TIME", pd.getTime());
		login.put("LOG_TYPE", "0");
		login.put("IP", request.getHeader("X-Real-IP"));
		login.put("BROWSER", request.getHeader("User-Agent"));
		login.put("REFERER", request.getHeader("Referer"));
		try {
			superDao.insert(TableName.TL_P_USER_LOGIN, login);
		} catch (Exception e) {
			logger.warn("记录登录日志出错", e);
		}
		logger.info("保存登录信息:" + login.toString());
	}

	/*
	 * private void getUserInfo() throws NumberFormatException,
	 * UnsupportedEncodingException { Result orderInfoResult = getSubsInfo();
	 * String orderInfo = ""; if (orderInfoResult.getCode() == 3) { orderInfo =
	 * "您使用的是VIP版"; } else if (orderInfoResult.getCode() == 2) { orderInfo =
	 * "您使用的是标准版"; } else { orderInfo = "您使用的是体验版"; } pd
	 * .setSessionAttribute(Constants.SESSION_USER_SUBSCRIBE_INFO, orderInfo);
	 * pd.setSessionAttribute(Constants.SESSION_USER_SUBSCRIBE,
	 * orderInfoResult); pd.setSessionAttribute(Constants.SESSION_NICK,
	 * pd.getTopVisitorNick());
	 * 
	 * String shopURL = topService.getShopURL(pd.getTopVisitorNick());
	 * pd.setSessionAttribute(Constants.SESSION_SHOP, shopURL); }
	 * 
	 * 
	 * private Result getSubsInfo() { String versionNo =
	 * pd.getRequestParameter("versionNo"); Result orderInfoResult = new
	 * Result(1, "体验版"); if ("3".equals(versionNo)) {
	 * orderInfoResult.setCode(3); orderInfoResult.setMsg("VIP版"); } else if
	 * ("2".equals(versionNo)) { orderInfoResult.setCode(2);
	 * orderInfoResult.setMsg("标准版"); } return orderInfoResult; }
	 */

	public String logout() {
		pd.getSession().invalidate();
		return SUCCESS;
	}
}
